<template>
  <Dialog ref="dialogRef" @submit="handleSubmit" :title="title" width="850px" height="500px">
    <div class="main-box" style="width: 100%; height: 500px">
      <div class="table-box">
        <Table
          ref="tableRef"
          :row-key="rowKey"
          :columns="columns"
          :request-api="requestApi"
          :pagination="pagination"
          :tool-button="toolButton"
        ></Table>
      </div>
      <div class="card" style="width: 250px; margin-left: 10px">
        <ElTable :row-key="rowKey" border :data="selectedList" :show-header="false">
          <ElTableColumn :prop="rowName" show-overflow-tooltip :label="label"></ElTableColumn>
          <ElTableColumn label="操作" width="80px">
            <template #default="{ row }">
              <ElButton type="danger" link icon="delete" @click="handleRemove(row)"></ElButton>
            </template>
          </ElTableColumn>
        </ElTable>
      </div>
    </div>
  </Dialog>
</template>

<script setup lang="ts" name="SelectDialog">
import { Dialog, useDialog } from "@/components/Dialog";
import { Table } from "@/components/Table";
import { ElTable, ElTableColumn, ElButton } from "element-plus";
import { ref, defineEmits, nextTick, computed, ComputedRef } from "vue";
import { ColumnProps } from "@/components/Table/type";
const dialogRef = ref();
const tableRef = ref();
const dialog = useDialog(dialogRef);
const props = defineProps({
  title: {
    type: String
  },
  requestApi: {
    type: Function
  },
  columns: {
    type: Array<ColumnProps>
  },
  rowKey: {
    type: String,
    default: "id"
  },
  rowName: {
    type: String
  },
  pagination: {
    type: Boolean,
    default: true
  },
  toolButton: {
    type: Boolean,
    default: false
  }
});
const emit = defineEmits(["submit"]);
const handleSubmit = () => {
  const selectedList = tableRef.value.selectedList;
  emit("submit", selectedList);
  dialog.close();
};
const handleRemove = row => {
  const rowValue = row[props.rowKey];
  if (rowValue) {
    for (const index in tableRef.value.selectedList) {
      const selected = tableRef.value.selectedList[index];
      if (selected[props.rowKey] === rowValue) {
        tableRef.value.selectedList.splice(index, 1);
        tableRef.value.toggleRowSelection(selected, false);
        break;
      }
    }
  }
};
const label: ComputedRef<String> = computed(() => {
  let label: String = "名称";
  for (const column of props.columns!) {
    if (column.prop === props.rowName) {
      label = column.label as String;
      break;
    }
  }
  return label;
});
const open = async () => {
  if (props.columns![0]!.type !== "selection") {
    props.columns?.splice(0, 0, { type: "selection", reserveSelection: true, label: "#", width: 50 });
  }
  await dialog.open();
  await nextTick();
  tableRef.value.clearSelection();
};
const selectedList = computed(() => {
  return tableRef.value?.selectedList || [];
});
defineExpose({ open });
</script>

<style scoped></style>
